package com.zdkj.admin.job;

import com.zdkj.admin.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by haonan on 2020/1/17
 * @deprecated 定时清理过期日志
 */
@Slf4j
@Component
public class SysLogDeleteJob {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private SysLogService sysLogService;

    private static final String LOCK_KEY = "sys_log_delete_key";

    private static final int TASK_TIMEOUT = 55;

    /**
     * 定时清理过期日志
     */
    @Scheduled(fixedRate = 24*60*60*1000) //每24个小时执行一次
    public void deleteLog(){

        RLock lock =  redissonClient.getLock(LOCK_KEY);
        boolean isLocked = false;
        try {
            isLocked = lock.tryLock(TASK_TIMEOUT,TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("lock to "+LOCK_KEY+" interrupted",e);
        }
        if(isLocked){
            log.info("start to clean expire sys log task");
            int count = sysLogService.deleteExpireLogs();
            log.info("clean {} logs",count);
        }else{
            log.info("lock to "+LOCK_KEY+" failed");
        }
    }
}
